package com.otp.fragment;

import android.annotation.TargetApi;
import android.app.Fragment;
import android.content.ContentUris;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.otp.Activity.R;
import com.otp.Activity.UserActivity;
import com.otp.Activity.UserProfileActivity;
import com.otp.util.Constants;
import com.otp.util.HttpUtil;
import com.otp.util.UploadFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ProfileFragment extends Fragment implements View.OnClickListener, UploadFile.OnUploadProcessListener {

    private RelativeLayout login = null;
    private TextView goNext = null;
    private TextView userNameText = null;
    private String userName = null;
    private ImageView profileImage = null;

    public static final int TAKE_PHOTO = 1;
    public static final int CROP_PHOTO = 2;
    public static final int CHOOSE_PHOTO = 3;
    private Uri imageUri;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_profile, container, false);
        this.registerForContextMenu(view);
        login = (RelativeLayout) view.findViewById(R.id.login);
        login.setOnClickListener(this);
        goNext = (TextView) view.findViewById(R.id.goLogin);
        userNameText = (TextView) view.findViewById(R.id.profile_userName);
        Typeface iconfont = Typeface.createFromAsset(getResources().getAssets(), "iconfont.ttf");
        goNext.setTypeface(iconfont);
        goNext.getPaint().setFakeBoldText(true);
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences(Constants.USER_DATA, 0);
        userName = sharedPreferences.getString(Constants.USER_NAME, "");
        if (userName.length() > 0) {
            userNameText.setText(userName);
        }
        profileImage = (ImageView) view.findViewById(R.id.profile_image);
        profileImage.setOnClickListener(this);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences(Constants.USER_DATA, 0);
        userName = sharedPreferences.getString(Constants.USER_NAME, "");
        if (userName.length() > 0) {
            userNameText.setText(userName);
        } else {
            userNameText.setText(R.string.click_to_login);
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences(Constants.USER_DATA, 0);
        String userName = sharedPreferences.getString(Constants.USER_NAME, "");
        switch (v.getId()) {
            case R.id.login:
                Log.e("usreName", userName);
                if (null == userName || "".equals(userName)) {
                    intent.setClass(getActivity(), UserActivity.class);
                } else {
                    intent.setClass(getActivity(), UserProfileActivity.class);
                }
                startActivity(intent);
                break;
            case R.id.profile_image:
                //this.getActivity().openOptionsMenu();
                if (null == userName || "".equals(userName)) {
                    intent.setClass(getActivity(), UserActivity.class);
                    startActivity(intent);
                } else {
                    this.getActivity().openContextMenu(this.getView());
                }
                // takePhoto();
                break;
            default:
                ;
                break;
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        this.getActivity().getMenuInflater().inflate(R.menu.avatar_menu, menu);
        super.onCreateContextMenu(menu, v, menuInfo);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        super.onContextItemSelected(item);
        Log.e("id", item.getItemId() + "");
        switch (item.getItemId()) {
            case R.id.from_album:
                getPhotoFromAlbum();
                ;
                break;
            case R.id.from_camera:
                takePhoto();
                ;
                break;
        }
        return true;
    }

    public void takePhoto() {
        File outputImage = new File(Environment.getExternalStorageDirectory(), "otp_avatar.jpg");
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
            imageUri = Uri.fromFile(outputImage);
            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            startActivityForResult(intent, TAKE_PHOTO);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void getPhotoFromAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, CHOOSE_PHOTO);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == this.getActivity().RESULT_OK) {
                    Intent intent = new Intent("com.android.camera.action.CROP");
                    intent.setDataAndType(imageUri, "image/*");
                    intent.putExtra("scale", true);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                    startActivityForResult(intent, CROP_PHOTO);
                }
                break;
            case CROP_PHOTO:
                try {
                    Bitmap bitmap = BitmapFactory.decodeStream(this.getActivity().getContentResolver().openInputStream(imageUri));
                    profileImage.setImageBitmap(bitmap);
                    uploadImage(imageUri,null);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                break;
            case CHOOSE_PHOTO:
                if (resultCode == this.getActivity().RESULT_OK) {
                    if (Build.VERSION.SDK_INT >= 19) {
                        handleImageOnKitKat(data);
                    } else {
                        handleImageBeforeKitKat(data);
                    }
                }
                ;
                break;
        }
    }

    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this.getActivity(), uri)) {
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            imagePath = getImagePath(uri, null);
        }
        disPlayImage(imagePath);
    }

    private void handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        disPlayImage(imagePath);
    }

    private void disPlayImage(String imagePath) {
        Log.e("ImagePath:",imagePath);
        if (imagePath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            profileImage.setImageBitmap(bitmap);
            uploadImage(null,imagePath);
        } else {
            Toast.makeText(this.getActivity(), "获取图片失败，请重试!", Toast.LENGTH_LONG).show();
        }
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        Cursor cursor = this.getActivity().getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                imageUri = uri;
            }
            cursor.close();
        }
        return path;
    }

    private void uploadImage(Uri uri,String imageUrl) {
        UploadFile uploadFile = UploadFile.getInstance();
        uploadFile.setConnectTimeout(3000);
        uploadFile.setOnUploadProcessListener(this);
        if (imageUrl == null && uri != null) {
            uploadFile.uploadFile(uri.getPath(), "file", HttpUtil.getURL("User/uploadImg"), null);
        } else {
            uploadFile.uploadFile(imageUrl, "file", HttpUtil.getURL("User/uploadImg"), null);
        }
    }
    @Override
    public void onUploadDone(int responseCode, String message) {

    }

    @Override
    public void onUploadProcess(int uploadSize) {

    }

    @Override
    public void initUpload(int fileSize) {

    }

}
